/**
 * 
 */
package com.kahweh.ngphoto.db;

import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;

import com.kahweh.ngphoto.bean.KProperty;

/**
 * @author Michael
 *
 */
public class PropertyUtil {
	private static final Logger LOG = Logger.getLogger(PropertyUtil.class.getName());
	/**
	 * @param section
	 * @param name
	 * @return
	 */
	public static KProperty getKProperty(String section, String name) {
		KProperty p = null;
		
    	if (section == null) section = "";
    	if (name == null || "".equals(name)) return null;

    	PersistenceManager pm = PMF.get().getPersistenceManager();
    	String query = "select from " + KProperty.class.getName() + " " +
    			"where section == sectionParam && " +
    			"name == nameParam " +
    			"parameters String sectionParam, String nameParam";
    	try {
    	    List<KProperty> properties = (List<KProperty>)pm.newQuery(query).execute(section, name);
    	    if (!properties.isEmpty()) {
    	    	p = properties.get(0);
    	    }
    	} finally {
    		pm.close();
    	}
    	
    	return p;
	}

    /**
     * @param section
     * @param name
     * @return
     */
    public static String getStringProperty(String section, String name) {
    	KProperty p = getKProperty(section, name);
    	
    	if (p == null) return null;
    	
    	return p.getValue();
    }
    
    /**
     * @param section
     * @param name
     * @return
     */
    public static Long getLongProperty(String section, String name) {
    	KProperty p = getKProperty(section, name);
    	
    	if (p == null) return null;
    	
    	if (!"Long".equalsIgnoreCase(p.getType())) return null;
    	
        String str = p.getValue();
        
        Long rtn = null;
        
        try {
        	rtn = Long.parseLong(str);
        } catch (NumberFormatException e) {
        	LOG.warning("Wrong Long format!");
        }

        return 0L;
    }
}
